#pragma once
#include<iostream>
#include<cstdio>
#include<string>
#include<unistd.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>

class udpServer
{
  private:
   // std::string ip;
    int port;
    int sock;
  public:
    udpServer(int _port = 8088)
      //:ip(_ip)
      :port(_port)
  {}
    void initServer()
    {
       sock = socket(AF_INET,SOCK_DGRAM,0);
       std::cout<<"sock:"<<sock<<std::endl;
       struct sockaddr_in local;
       local.sin_family = AF_INET;
       local.sin_port = htons(port);//主机序列转成网络序列
       //local.sin_addr.s_addr = inet_addr(ip.c_str());
       local.sin_addr.s_addr = INADDR_ANY;

       //开始绑定
       //绑定失败就直接退出
       if(bind(sock,(struct sockaddr*)&local,sizeof(local)) < 0)
       {
         std::cerr<<"bind error"<<std::endl;
         exit(1);
       
       }
    }
    void start()
    {
      char msg[64];
         for(;;)
         {
           msg[0] = '\0';
           //从远端接收
            struct sockaddr_in end_point;
            socklen_t len = sizeof(end_point);
            ssize_t s = recvfrom(sock,msg,sizeof(msg)-1,0,(struct sockaddr*)&end_point,&len);
            if(s > 0 )
            {
              msg[s] = '\0';
              std::cout<<"client:"<<msg<<std::endl;
              std::string echo_string = msg;
              echo_string += "[srever echo]";
              sendto(sock,echo_string.c_str(),echo_string.size(),0,
                    (struct sockaddr*)&end_point,len);
            }
         }
    }
    ~udpServer()
    {
       close(sock);
    }
};

